import React, { Component } from 'react'
import {
  Card,
  Select,
  Table,
  Button,
  Input,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { APIGetProducts, APISearchProducts, APIUpdateStatus } from '../../api'
import { PAGE_SIZE } from '../../utils/constants'

const { Option } = Select
export default class ProductHome extends Component {
  state = {
    total: 0,
    products: [],
    loading: false,
    searchName: '',
    searchType: 'productName'
  }

  // 获取指定页面的商品
  getProducts = async (pageNum) => {
    this.pageNum = pageNum
    this.setState({loading: true})

    let result
    const { searchName, searchType } = this.state
    if(searchName) {
      result = await APISearchProducts({pageNum, pageSize: PAGE_SIZE, searchName, searchType})
    } else {
      result = await APIGetProducts(pageNum, 3)
    }

    
    this.setState({loading: false})
    if(result.status === 0) {
      const { total, list } = result.data
      this.setState({
        total,
        products: list
      })
    }
  }
  // 更新指定商品的状态
  updateStatus = async (productId, status) => {
    const result = await APIUpdateStatus(productId, status)
    if(result.status === 0) {
      message.success('更新商品成功')
      this.getProducts(this.pageNum)
    }
  }

  // 初始化表格头
  initColums = () => {
    this.columns = [
      {
        title: '商品名称',
        dataIndex: 'name'
      },
      {
        title: '商品描述',
        dataIndex: 'desc'
      },
      {
        title: '价格',
        dataIndex: 'price',
        render: (price) => '￥' + price        
      },
      {
        width: 100,
        title: '状态',
        // dataIndex: 'status',
        render: (product) => {
          const { status, _id } = product
          const newStatus = status === 1 ? 2 : 1
          return (
            <span>
              <Button 
                type="primary" 
                onClick={() => this.updateStatus(_id, newStatus)}
              >
                {status === 1 ? '下架' : '上架'}
              </Button>
              <span>{status === 1 ? '在售' : '已下架'}</span>
            </span>
          )
        }   
      },
      {
        width: 100,
        title: '操作',
        render: (product) => {
          return (
            <span>
              {/* 将product作为state传递给目标路由组件 */}
              <Button type="link" onClick={() => this.props.history.push('/product/detail', {product})}>详情</Button>
              <Button type="link" onClick={() => this.props.history.push('/product/addupdate', product)}>修改</Button>
            </span>
          )
        }   
      }
    ];
  }
  componentDidMount() {
    this.getProducts(1)
  }
  render() {
    const { 
      products, 
      total, 
      loading,
      searchType,
      searchName
    } = this.state
    
    this.initColums()
    const title = (
      <span>
        <Select 
          value={searchType} 
          style={{width: 150}} 
          onChange={value => this.setState({searchType: value})}
        >
          <Option value='productName'>按名称搜索</Option>
          <Option value='productDesc'>按描述搜索</Option>
        </Select>
        <Input 
          value={searchName} 
          onChange={event => this.setState({searchName: event.target.value})}
          placeholder='关键字' 
          style={{width: 150, margin: '0 15px'}}
        />
        <Button type="primary" onClick={() => this.getProducts(1)}>搜索</Button>
      </span>
    )

    const extra = (
      <Button type="primary" onClick={() => this.props.history.push('/product/addupdate')}>
        <PlusOutlined />
        添加商品
      </Button>
    )

    return (
      <Card title={title} extra={extra}>
        <Table 
          loading={loading}
          bordered
          dataSource={products} 
          columns={this.columns} 
          rowKey='_id'
          pagination={{
            current: this.pageNum,
            defaultPageSize: PAGE_SIZE, 
            showQuickJumper: true, 
            total,
            onChange: this.getProducts
          }}
        />
      </Card>
    )
  }
}
